package com.sky.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        /**
         * 除了异常情况
         */
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        Long currentId = BaseContext.getCurrentId();


        /**
         * 插入一条下但
         */
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Orders.UN_PAID);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setPhone(addressBook.getPhone());
        order.setUserId(currentId);
        orderMapper.insert(order);

        /**
         * 插入n条下单明细
         */
        /**
         * select * from shopping_cart where user_id = ?
         */
        ShoppingCart params = ShoppingCart.builder().userId(currentId).build();


        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(params);
        if (shoppingCartList == null || shoppingCartList.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }


        /**
         * insert into aaaa ( ？？？？） values （ ????）
         */
        List<OrderDetail> orderDetails = new ArrayList<>();

        shoppingCartList.forEach(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setId(null);
            orderDetail.setOrderId(order.getId());
            orderDetails.add(orderDetail);
        });

        orderDetailMapper.insertBatch(orderDetails);


        /**
         * 清空购物车
         */
        shoppingCartMapper.deleteByUserId(currentId);


        /**
         * 返回需要的数据
         */
        OrderSubmitVO submitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderAmount(order.getAmount())
                .orderNumber(order.getNumber())
                .orderTime(order.getOrderTime())
                .build();

        return submitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        Integer OrderPaidStatus = Orders.PAID;
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;

        LocalDateTime check_out_time = LocalDateTime.now();

        String orderNumber = ordersPaymentDTO.getOrderNumber();

        log.info("调用updateStatus，用于替换微信职位更新数据库状态的问题");

        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, orderNumber);
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        HashMap map = new HashMap();
        map.put("type",1);
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);
        String json = JSONObject.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {

        /**
         * select * from xxxx where userId=xxx
         */
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

//        Orders order = new Orders();
//        BeanUtils.copyProperties(ordersPageQueryDTO, order);

        Long currentId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(currentId);


        Page<Orders> orderList = orderMapper.pageQuery(ordersPageQueryDTO);

        ArrayList<OrderDetailVO> orderDetailVOS = new ArrayList<>();
        List<Orders> result = orderList.getResult();
        for (Orders o : result) {

            OrderDetailVO vo = new OrderDetailVO();
            BeanUtils.copyProperties(o, vo);

            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(o.getId());
            vo.setOrderDetailList(orderDetailList);
            orderDetailVOS.add(vo);
        }

        return new PageResult(orderList.getTotal(), orderDetailVOS);
    }

    /**
     * 查询订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderDetailVO orderDetail(Integer orderId) {
        Orders order = orderMapper.getById(orderId);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(Long.valueOf(orderId));

        OrderDetailVO vo = new OrderDetailVO();
        BeanUtils.copyProperties(order, vo);
        vo.setOrderDetailList(orderDetailList);
        return vo;
    }

    /**
     * 取消订单
     *
     * @param orderId
     */
    @Override
    public void cancel(Integer orderId) {
        Orders orders = Orders.builder()
                .id(Long.valueOf(orderId))
                .status(Orders.CANCELLED)
                .build();
        orderMapper.update(orders);
        /**
         * 退款
         */
    }

    /**
     * 再来一单
     *
     * @param orderId
     */
    @Transactional
    @Override
    public void repetition(Integer orderId) {
        Orders order = orderMapper.getById(orderId);
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(Long.valueOf(orderId));
        order.setId(null);


        Long currentId = BaseContext.getCurrentId();
        /**
         * 插入一条
         */
        order.setOrderTime(LocalDateTime.now());
        order.setPayStatus(Orders.UN_PAID);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(currentId);
        orderMapper.insert(order);
        /**
         * 插入n条
         */
        orderDetailList.forEach(orderDetail -> {
            orderDetail.setOrderId(order.getId());
        });
        orderDetailMapper.insertBatch(orderDetailList);
    }

    /**
     * 订单搜索
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult condtionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> orders = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderConditionSearchVO> searchVOS = new ArrayList<>();
        orders.forEach(o->{
            OrderConditionSearchVO vo = new OrderConditionSearchVO();
            BeanUtils.copyProperties(o,vo);

            /**
             * 拼dishes字符串
             */
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(o.getId());
            StringBuilder orderDishes =new StringBuilder();
            orderDetailList.forEach(orderDetail -> {
                orderDishes.append(orderDetail.getName()+"+");
            });
            orderDishes.deleteCharAt(orderDishes.lastIndexOf("+"));
            vo.setOrderDishes(orderDishes.toString());

            searchVOS.add(vo);
        });
        return new PageResult(orders.getTotal(),searchVOS);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {

        OrderStatisticsVO VO = new OrderStatisticsVO();
        List<StatusCount> counts = orderMapper.CountsByStatus();
        for (StatusCount o : counts) {
            if (o.getStatus()==Orders.CONFIRMED){
                VO.setConfirmed(o.getCount());
            }else if (o.getStatus() == Orders.DELIVERY_IN_PROGRESS){
                VO.setDeliveryInProgress(o.getCount());
            } else if (o.getStatus() == Orders.TO_BE_CONFIRMED) {
                VO.setToBeConfirmed(o.getCount());
            }
        }
        return VO;
    }

    /**
     * 拒单
     * @param ordersRejectionDTO
     */
    @Transactional
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders order=new Orders();
        order.setId(ordersRejectionDTO.getId());
        order.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        order.setStatus(Orders.REFUND);

        /**
         * 还要微信支付退钱给它。这里没有写
         */
        refund();
        orderMapper.update(order);
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders order=new Orders();
        order.setId(ordersConfirmDTO.getId());
        order.setStatus(Orders.CONFIRMED);
//        order.setCheckoutTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders order=Orders.builder()
                .cancelReason(ordersCancelDTO.getCancelReason())
                .id(ordersCancelDTO.getId())
                .cancelTime(LocalDateTime.now())
                .status(Orders.CANCELLED)
                .build();
        orderMapper.update(order);

        /**
         * 退款
         */
        refund();
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Integer id) {
        LocalDateTime now = LocalDateTime.now();
        Orders order=Orders.builder()
                .id(Long.valueOf(id))
                .status(Orders.DELIVERY_IN_PROGRESS)
                .estimatedDeliveryTime(now.plusMinutes(30))
                .build();
        orderMapper.update(order);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Integer id) {
        Orders order=Orders.builder()
                .status(Orders.COMPLETED)
                .id(id.longValue())
                .deliveryTime(LocalDateTime.now())
                .build();
        orderMapper.update(order);
    }

    //    TODO 退款
    private void refund(){

    }

}
